<?php

/**
 * TemplateController is the default controller for this application
 */
class TemplateController extends ControllerBase {
	/**
	 * TemplateDataService Object
	 *
	 * @var TemplateDataService object
	 */
	private $templateDataService = null;
	
	/**
	 *
	 * Template Category Data Service
	 * @var TemplateCategoryDataService object
	 */
	private $templateCategoryDataService = null;
	
	/**
	 * TemplatePhotoDataService Object
	 *
	 * @var TemplatePhotoDataService object
	 */
	private $templatePhotoDataService = null;
	
	/**
	 * SettingsDataService Object
	 * @var SettingsDataService object
	 */
	private $settingsDataService = NULL;
	
	public function __construct() {
		parent::__construct ();
		
		// Set page name
		$this->setPageName ( 'templates' );
		
		// Init Authentication class
		$authentication = new Authentication ();
		
		// Only administrator can right
		if ($authentication->isAdministrator () == false) {
			
			// Go to login page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Login/index';
			CommonUtils::redirect ( $url );
		}
		
		// Get status list of AdminBlog category
		$this->smarty->assign ( 'statusList', TemplateEntity::getStatusList () );
		
		// Initialize TemplateDataService
		$this->templateDataService = new TemplateDataService ();
		$this->templateCategoryDataService = new TemplateCategoryDataService ();
		$this->templatePhotoDataService = new TemplatePhotoDataService ();
		$this->settingsDataService = new SettingsDataService ();
		$this->usersDataService = new UsersDataService ();
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site. Return list of all product category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function indexAction() {
		$this->listAction ();
	}
	
	/**
	 * Dispplay List of Templates
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function listAction() {
		$arrElement = array ();
		$arrElement ['status'] = TemplateEntity::ACTIVE;
		$numRecordPerPage = ITEM_PER_PAGE;
		
		// Pager
		$start = $this->getQuery ( 'start', 0 );
		if ($start == '' || $start < 0) {
			$start = 0;
		}
		
		// Get Totals Templates
		$totals = $this->templateDataService->getTotals ( $arrElement );
		
		$itemList = $this->templateDataService->getItems ( $arrElement, NULL, $start, $numRecordPerPage );
		
		if ($start > $totals) {
			$start = 0;
		}
		$link = Zend_Registry::get ( 'config' )->APPLICATION_URL . "/Admin/Template/Index";
		$pageLink = '';
		if ($totals > $numRecordPerPage) {
			$pageUtils = new PagerUtils ( $start, $totals, $numRecordPerPage, 10, $link );
			$pageLink = $pageUtils->writePagesLinks ( 0, 'start' );
			$pageLink .= "<br><span class=\"paing_text_nolink\">" . $pageUtils->writePagesCounter () . "</span>";
		}
		
		// Get Demo TemplateId
		//$demoTemplateSettings = $this->settingsDataService->getItem(SETTINGS_DEMO_TEMPLATE);
		//$demoTemplateId = $demoTemplateSettings->value;
		

		$demoUser = $this->usersDataService->getByUserName ( DEMO_USERNAME );
		if ($demoUser) {
			$this->smarty->assign ( 'demoTemplateId', $demoUser->mainTemplateId );
		}
		
		$this->smarty->assign ( 'itemList', $itemList );
		
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'pageLink', $pageLink );
		$this->createActionKey ();
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Template/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Add action is trigger when admin want to add the product_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function addAction() {
		// Get action key
		$actionKey = $this->getPost ( 'actionKey', '' );
		$isError = false;
		$error = "";
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit' && (isset ( $_SESSION ['tokenKey'] ) && $actionKey == $_SESSION ['tokenKey'])) {
			
			// get content
			$description = $this->getPost ( 'description', "" );
			$description = trim ( $description );
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$description = stripslashes ( $description );
			}
			
			$categoryId = $this->getPost ( 'categoryId', "" );
			
			// Upload picture
			$picture = '';
			try {
				$picture = CommonUtils::uploadPictureEx ( 'picture' );
			} catch ( Exception $ex ) {
				
				// Ignore this case
				$resultMessage = 'Upload Picture fail.';
			}
			
			$package = '';
			try {
				$package = CommonUtils::uploadTemplate ( 'package' );
			} catch ( Exception $ex ) {
				// Ignore this case
				$resultMessage = 'Upload Template fail.';
			}
			
			// Get name field
			$name = $this->getPost ( 'name', '' );
			$status = $this->getPost ( 'status', '' );
			
			try {
				// Save data into database
				$templateEntity = $this->templateDataService->beforeCreate ();
				$templateEntity->name = $name;
				$templateEntity->description = $description;
				$templateEntity->status = $status;
				$templateEntity->folder = "template1";
				$templateEntity->categoryId = $categoryId;
				$templateEntity->picture = $picture;
				$res = $this->templateDataService->create ( $templateEntity );
				
				// Create new Template Screen Shot
				$templatePhotoEntity = $this->templatePhotoDataService->beforeCreate ();
				$templatePhotoEntity->picture = $picture;
				$templatePhotoEntity->title = "Default Photo";
				$templatePhotoEntity->status = TemplatePhotoEntity::ACTIVE;
				$templatePhotoEntity->description = "";
				$templatePhotoEntity->url = "";
				$templatePhotoEntity->viewed = 0;
				$templatePhotoEntity->comment = "";
				$templatePhotoEntity->templateId = $res;
				$templatePhotoId = $this->templatePhotoDataService->create ( $templatePhotoEntity );
				
				// Update new folder name via "template" . $index (ID of template)
				$templateEntity->id = $res;
				$templateEntity->folder = "template" . $res;
				$templateEntity->picture = strval ( $templatePhotoId );
				$this->templateDataService->update ( $templateEntity );
				
				//Handle Extraction here
				$this->handleTemplateFile ( $package, $templateEntity->id );
				
				$this->smarty->assign ( 'name', isset ( $isError ) ? $name : $templateEntity->name );
				$this->smarty->assign ( 'categoryId', isset ( $isError ) ? $categoryId : $templateEntity->categoryId );
				$this->smarty->assign ( 'picture', isset ( $isError ) ? $picture : $templateEntity->picture );
				$this->smarty->assign ( 'description', isset ( $isError ) ? $description : $templateEntity->description );
				$this->smarty->assign ( 'status', isset ( $isError ) ? $status : $templateEntity->status );
				
				// Show a message
				$error = 'The item has been created successfully';
			} catch ( Exception $ex ) {
				$isError = true;
				
				$this->smarty->assign ( 'name', isset ( $isError ) ? $name : $templateEntity->name );
				$this->smarty->assign ( 'categoryId', isset ( $isError ) ? $categoryId : $templateEntity->categoryId );
				$this->smarty->assign ( 'picture', isset ( $isError ) ? $picture : $templateEntity->picture );
				$this->smarty->assign ( 'description', isset ( $isError ) ? $description : $templateEntity->description );
				
				// Ignore to process this case. Only show a message
				$error = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
			}
		}
		
		// Create new token key
		$_SESSION ['tokenKey'] = sha1 ( CommonUtils::randomNumber ( 10 ) );
		
		$this->smarty->assign ( 'categoryList', $this->templateCategoryDataService->getItems ( NULL ) );
		$this->smarty->assign ( 'error', isset ( $error ) ? $error : '' );
		$this->smarty->assign ( 'isError', isset ( $isError ) ? $isError : false );
		$this->smarty->assign ( 'actionKey', $_SESSION ['tokenKey'] );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Template/add.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Edit action is trigger when admin want to edit the product_category information
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function editAction() {
		// Error flag
		$isError = false;
		$error = "";
		
		//$max_upload = (int)(ini_get('upload_max_filesize'));
		//echo $max_upload;
		//die();
		

		// Get id of product_category
		$id = $this->getPost ( 'id', '' );
		if (is_null ( $id ) || $id == '') {
			$id = $this->getQuery ( 'id', '' );
		}
		// If the id of product_category does not exist, go on to view list page
		if (empty ( $id )) {
			$this->listAction ();
			return - 1;
		}
		
		// Get action key
		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit' && (isset ( $_SESSION ['tokenKey'] ) && $actionKey == $_SESSION ['tokenKey'])) {
			
			// Get id field
			$id = $this->getPost ( 'id', '' );
			
			// get content
			$description = $this->getPost ( 'description', "" );
			$description = trim ( $description );
			// remove magic quotes
			if (get_magic_quotes_gpc ()) {
				$description = stripslashes ( $description );
			}
			
			$categoryId = $this->getPost ( 'categoryId', "" );
			
			// Upload picture
			$picture = '';
			try {
				$picture = CommonUtils::uploadPictureEx ( 'picture' );
			} catch ( Exception $ex ) {
				
				// Ignore this case
				$resultMessage = 'Upload banner fail.';
			}
			
			$package = '';
			try {
				$package = CommonUtils::uploadTemplate ( 'package' );
			} catch ( Exception $ex ) {
				// Ignore this case
				$resultMessage = 'Upload Template fail.';
			}
			
			// Get name field
			$name = $this->getPost ( 'name', '' );
			$status = $this->getPost ( 'status', '' );
			
			try {
				// Save data into database
				$templateEntity = $this->templateDataService->beforeUpdate ( $id );
				if (is_null ( $templateEntity )) {
					throw new Exception ( 'The id of product_category does not exist', 1 );
				}
				
				$templateEntity->name = $name;
				$templateEntity->description = $description;
				$templateEntity->categoryId = $categoryId;
				if ($picture != "") {
					$templateEntity->picture = $picture;
				}
				$templateEntity->status = $status;
				
				if (! empty ( $package )) {
					
					$this->handleTemplateFile ( $package, $id );
				}
				
				$res = $this->templateDataService->update ( $templateEntity );
				// Show a message
				$error = 'The record has been updated successfully';
			} catch ( Exception $ex ) {
				// Ignore to process this case. Only show a message
				$error = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
				$isError = true;
			}
		}
		
		// View data
		$templateEntityDetail = $this->templateDataService->getById ( $id );
		
		// If the id of product_category not exist, go on to view list page
		if (is_null ( $templateEntityDetail ) || is_null ( $templateEntityDetail )) {
			$this->listAction ();
			return - 1;
		}
		
		// Error Handling
		$this->smarty->assign ( 'isError', $isError );
		// Create new token key
		$_SESSION ['tokenKey'] = sha1 ( CommonUtils::randomNumber ( 10 ) );
		$this->smarty->assign ( 'categoryList', $this->templateCategoryDataService->getItems ( NULL ) );
		$this->smarty->assign ( 'error', isset ( $error ) ? $error : '' );
		$this->smarty->assign ( 'actionKey', $_SESSION ['tokenKey'] );
		$this->smarty->assign ( 'id', ($isError == true) ? $id : $templateEntityDetail->id );
		$this->smarty->assign ( 'name', ($isError == true) ? $name : $templateEntityDetail->name );
		$this->smarty->assign ( 'description', ($isError == true) ? $description : $templateEntityDetail->description );
		$this->smarty->assign ( 'categoryId', ($isError == true) ? $categoryId : $templateEntityDetail->categoryId );
		$this->smarty->assign ( 'picture', ($isError == true) ? $picture : $templateEntityDetail->picture );
		$this->smarty->assign ( 'templateEntity', $templateEntityDetail );
		$this->smarty->assign ( 'status', ($isError == true) ? $status : $templateEntityDetail->status );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Template/edit.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**
	 * Active some records of product_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function activeAction() {
		$this->updateStatus ( TemplateEntity::ACTIVE );
		
		// View product_category list
		$this->listAction ();
	}
	
	/**
	 * Inactive some records of product_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function inactiveAction() {
		$this->updateStatus ( TemplateEntity::INACTIVE );
		
		// View product_category list
		$this->listAction ();
	}
	
	/**
	 * Delete action is trigger when administrator want to delete a product_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function deleteAction() {
		// Get action key
		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get Id of product_category
		$id = $this->getPost ( 'idValue', '' );
		
		// Delete all Template Photo
		$this->templatePhotoDataService->removePhoto ( $id );
		
		// Delete a product_category item
		$res = $this->templateDataService->del ( $id );
		
		// Update all User Template to default 
		$arrElement = array ();
		$arrElement ['mainTemplateId'] = $id;
		$listUsers = $this->usersDataService->getItems ( $arrElement );
		if (is_array ( $listUsers )) {
			foreach ( $listUsers as $user ) {
				$user->mainTemplateId = DEFAULT_TEMPLATE_ID;
				$this->usersDataService->update ( $user );
			}
		}
		
		// View product_category list
		$this->listAction ();
	}
	
	/**
	 * Delete list of product_category
	 *
	 * @access public
	 *
	 * @return void
	 */
	public function deleteallAction() {
		$iCount = $this->getPost ( 'iCount', 0 );
		for($i = 0; $i < $iCount; $i ++) {
			$id = $this->getPost ( 'checkItem' . $i, '' );
			if (! empty ( $id )) {
				// Delete all template photo
				$this->templatePhotoDataService->removePhoto ( $templateId );
				
				// Delete a product_category item
				$this->templateDataService->del ( $id );
			}
		}
		// View product_category list
		$this->listAction ();
	}
	
	/**
	 * Update status list of product_category
	 *
	 * @access private
	 *
	 * @param int $status: Status of the product_category
	 *
	 * @return void
	 */
	protected function updateStatus($status) {
		// Get action key
		$actionKey = $this->getPost ( 'actionKey', '' );
		if (isset ( $_SESSION ['tokenKey'] ) && $actionKey == $_SESSION ['tokenKey']) {
			$iCount = $this->getPost ( 'iCount', 0 );
			for($i = 0; $i < $iCount; $i ++) {
				$id = $this->getPost ( 'checkItem' . $i, '' );
				if (! empty ( $id )) {
					$this->templateDataService->updateStatus ( $id, $status );
				}
			}
		}
	}
	
	/**
	 * Set DEMO template
	 */
	public function setDemoAction() {
		$templateId = $this->getQuery ( 'id', '' );
		$templateEntity = $this->templateDataService->getById ( $templateId );
		if (empty ( $templateEntity )) {
			// Redirect to Template List Page
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Template';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		//$this->settingsDataService->setValue(SETTINGS_DEMO_TEMPLATE, intval($templateId));
		$demoUser = $this->usersDataService->getByUserName ( DEMO_USERNAME );
		if ($demoUser) {
			$demoUser->mainTemplateId = intval ( $templateId );
			$this->usersDataService->update ( $demoUser );
		}
		
		// Redirect to Template List Page
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Template';
		CommonUtils::redirect ( $url );
	}
	
	/**
	 * Handle Template Uploading
	 * @param string $filename
	 * @param string $templateId
	 */
	private function handleTemplateFile($filename, $templateId) {
		if (empty ( $filename ) || empty ( $templateId ))
			return false;
		$this->logger->log ( "Begin handleTemplateFile()", Zend_Log::DEBUG );
		
		$templateFile = UPLOADTEMPLATE_PATH . '/' . $filename;
		$zip = new dUnzip2 ( $templateFile, ZIP_FTP_ENABLE, ZIP_FTP_HOST, ZIP_FTP_USERNAME, ZIP_FTP_PASSWORD );
		// Activate debug
		$zip->debug = false;
		$templateFolder = "template" . $templateId;
		$targetDir = EXTRACT_TEMPLATE_PATH . '/' . $templateFolder;
		
		$win = stripos ( PHP_OS, 'win' ) !== false ? true : false;
		$zip->unzipAll ( $targetDir );
		if ($win == true) {
			$output = array ();
			$sourceDir = $targetDir . "/Layouts";
			$destinationDir = APPLICATION_LAYOUTS_PATH . "/" . $templateFolder;
			$command = 'xcopy "' . $sourceDir . '" "' . $destinationDir . '" /D /E /C /R /I /K /Y';
			exec ( $command, $output );
			$this->logger->log ( "Copying Layouts data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
			
			unset ( $output );
			$sourceDir = $targetDir . "/Views";
			$destinationDir = APPLICATION_VIEWS_PATH . "/" . $templateFolder;
			$command = 'xcopy "' . $sourceDir . '" "' . $destinationDir . '" /D /E /C /R /I /K /Y';
			exec ( $command, $output );
			$this->logger->log ( "Copying Views data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
			
			unset ( $output );
			$sourceDir = $targetDir . "/Themes";
			$destinationDir = APPLICATION_THEMES_PATH . "/" . $templateFolder;
			$command = 'xcopy "' . $sourceDir . '" "' . $destinationDir . '" /D /E /C /R /I /K /Y';
			exec ( $command, $output );
			$this->logger->log ( "Copying Themes data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
		} else {
			// Copy all Layouts files
			$output = array ();
			$sourceDir = $targetDir . "/Layouts";
			$destinationDir = APPLICATION_LAYOUTS_PATH . "/" . $templateFolder;
			if (! is_dir ( $destinationDir )) {
				// Make folder if it's not exist
				$command = "mkdir " . $destinationDir;
				exec ( $command );
			}
			
			$command = 'cp -r ' . $sourceDir . '/* ' . $destinationDir . '';
			exec ( $command, $output );
			$this->logger->log ( "Copying Layouts data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
			
			// Copy All Views files and folders
			unset ( $output );
			$sourceDir = $targetDir . "/Views";
			$destinationDir = APPLICATION_VIEWS_PATH . "/" . $templateFolder;
			if (! is_dir ( $destinationDir )) {
				// Make folder if it's not exist
				$command = "mkdir " . $destinationDir;
				exec ( $command );
			}
			$command = 'cp -r ' . $sourceDir . '/* ' . $destinationDir . '';
			
			exec ( $command, $output );
			$this->logger->log ( "Copying Views data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
			
			// Copy all Themes files and folder
			unset ( $output );
			$sourceDir = $targetDir . "/Themes";
			$destinationDir = APPLICATION_THEMES_PATH . "/" . $templateFolder;
			if (! is_dir ( $destinationDir )) {
				// Make folder if it's not exist
				$command = "mkdir " . $destinationDir;
				exec ( $command );
			}
			$command = 'cp -r ' . $sourceDir . '/* ' . $destinationDir . '';
			exec ( $command, $output );
			$this->logger->log ( "Copying Themes data ...", Zend_Log::DEBUG );
			$this->writeOutput ( $output );
		}
		
		$this->logger->log ( "End handleTemplateFile()", Zend_Log::DEBUG );
	
	}
	
	/**
	 * Write Output to Log file
	 * @param array $output
	 */
	private function writeOutput($output) {
		$str = "";
		foreach ( $output as $item ) {
			$str .= $item . "\r\n";
		}
		
		$this->logger->log ( $str, Zend_Log::DEBUG );
	}
}
